package com.mingmen.canting.zhenban;

import android.annotation.SuppressLint;
import android.arch.persistence.room.util.StringUtil;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.mingmen.canting.R;
import com.mingmen.canting.activity.CangKuListActivity;
import com.mingmen.canting.activity.LoginActivity;
import com.mingmen.canting.activity.QueRenLingQuActivity;
import com.mingmen.canting.activity.YiShenHeActivity;
import com.mingmen.canting.adapter.DaishenheListAdapter;
import com.mingmen.canting.adapter.YiShenHeListAdapter;
import com.mingmen.canting.base.BaseBean;
import com.mingmen.canting.definerecycleview.SwipeRecyclerView;
import com.mingmen.canting.defineview.ToastDialog;
import com.mingmen.canting.http.MyOkhttp;
import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.httpconfig.HttpResponse;

import com.mingmen.canting.model.EventBean;
import com.mingmen.canting.model.MyLiveList;
import com.mingmen.canting.model.ZhenBanShenHe;
import com.mingmen.canting.refresh.ClassicsFooter;
import com.mingmen.canting.refresh.ClassicsHeader;
import com.mingmen.canting.util.DividerItemDecoration;
import com.mingmen.canting.util.GsonUtil;
import com.mingmen.canting.util.MyStringUtils;
import com.mingmen.canting.util.SharePreferenceUtil;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;

@SuppressLint("ValidFragment")
public class YiShenHeListragment extends Fragment implements YiShenHeListAdapter.OnItemClickListener {

    @BindView(R.id.recyclerview)
    SwipeRecyclerView mRecyclerview;

    Unbinder unbinder;
    private String mTitle;


    private YiShenHeListAdapter yiShenHeListAdapter = null;
    private LinearLayoutManager mLinearLayoutManager;
    TimePickerView pvTime, pvTime2;
    @BindView(R.id.textview_calendafirst)
    TextView textview_calendafirst;
    @BindView(R.id.textview_calendasecond)
    TextView textview_calendasecond;

    public static YiShenHeListragment getInstance(String title) {
        YiShenHeListragment sf = new YiShenHeListragment();
        sf.mTitle = title;
        return sf;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    String token;
    List<ZhenBanShenHe.DataBean> dataBeanList = new ArrayList<>();
    @BindView(R.id.frame_layout)
    FrameLayout frame_layout;
    @BindView(R.id.layout_nodata)
    LinearLayout layout_nodata;
    @BindView(R.id.layout_calenda_first)
    LinearLayout layout_calenda_first;
    @BindView(R.id.layout_calenda_second)
    LinearLayout layout_calenda_second;
    String startTime = "";
    String endTime = "";
    @BindView(R.id.btn_digndan)
    Button btn_digndan;
    @BindView(R.id.btn_suofang)
    Button btnSuofang;
    @BindView(R.id.img_list)
    ImageView imgList;
    String data;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    int pageNumber = 1;
    int totalPage;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fr_yishenhe, null);
        TextView card_title_tv = (TextView) v.findViewById(R.id.card_title_tv);
        card_title_tv.setText(mTitle);
        EventBus.getDefault().register(this);
        unbinder = ButterKnife.bind(this, v);
        token = (String) SharePreferenceUtil.get(getActivity(), "token", "");
        initView();
        getCaneda();
//        initData();
        yiShenHeListAdapter = new YiShenHeListAdapter(getActivity(), dataBeanList);
        mLinearLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerview.setLayoutManager(mLinearLayoutManager);
        DividerItemDecoration itemDecorationHeader = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST);
        itemDecorationHeader.setDividerDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.divider_main_bg_height_1));
        mRecyclerview.addItemDecoration(itemDecorationHeader);
        mRecyclerview.setAdapter(yiShenHeListAdapter);
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        data = dateFormat.format(calendar.getTime());
        startTime = data;
        endTime = data;

        String replace_data = data.replace("-", ".");
        Log.d("replace_data", replace_data);
        textview_calendafirst.setText(replace_data);
        textview_calendasecond.setText(replace_data);

        getMyData(token, "1", "", "");
        initListener();
        refreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()));
        refreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()));

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {

                pageNumber = 1;
                getMyData(token, "1", "", "");

            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                if (pageNumber >= totalPage) {
                    Toast.makeText(getActivity(), "已到最后一页", Toast.LENGTH_SHORT).show();
                    refreshlayout.finishLoadMore(false);//传入false表示加载失败
                } else {
                    pageNumber++;

                    HttpResponse.daiShenhe(token, "1", startTime, endTime, "1", pageNumber,new StringCallback(getActivity()) {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            Log.d("YiShenHeshenHelist", s);

                            BaseBean baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                            if (baseBean.getCode() == 0) {
                                ZhenBanShenHe zhenBanShenHe = new ZhenBanShenHe();
                                zhenBanShenHe = GsonUtil.GsonToBean(s, ZhenBanShenHe.class);
                                totalPage=zhenBanShenHe.getTotalPage();

//                                dataBeanList = zhenBanShenHe.getData();
                                dataBeanList.addAll(zhenBanShenHe.getData());
                                if (dataBeanList.size() == 0) {

                                    layout_nodata.setVisibility(View.VISIBLE);
                                    mRecyclerview.setVisibility(View.GONE);
                                } else {
                                    layout_nodata.setVisibility(View.GONE);
                                    mRecyclerview.setVisibility(View.VISIBLE);
                                }

                                yiShenHeListAdapter.setDataList(dataBeanList);

                                Log.d("YiShenHe", zhenBanShenHe.getData().size() + "");

                            } else {
                                Toast.makeText(getActivity(), baseBean.getMessage(), Toast.LENGTH_SHORT).show();
                            }

                        }

                        @Override
                        public void onAfter(String s, Exception e) {
                            super.onAfter(s, e);
                            refreshLayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                            refreshLayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            super.onError(call, response, e);
                            Log.d("ONERROR", "ONERROER");
                            layout_nodata.setVisibility(View.VISIBLE);

                        }
                    });
                    refreshlayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
                }


            }
        });
        return v;
    }

    public void getMyData(String token, String st, String startTime, String endTime) {

        HttpResponse.daiShenhe(token, st, startTime, endTime, "1", 1,new StringCallback(getActivity()) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("YiShenHeshenHelist", s);

                BaseBean baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    ZhenBanShenHe zhenBanShenHe = new ZhenBanShenHe();
                    zhenBanShenHe = GsonUtil.GsonToBean(s, ZhenBanShenHe.class);
                    totalPage=zhenBanShenHe.getTotalPage();
                    if (dataBeanList.size() > 0) {
                        dataBeanList.clear();
                    }
                    dataBeanList = zhenBanShenHe.getData();
                    if (dataBeanList.size() == 0) {

                        layout_nodata.setVisibility(View.VISIBLE);
                        mRecyclerview.setVisibility(View.GONE);
                    } else {
                        layout_nodata.setVisibility(View.GONE);
                        mRecyclerview.setVisibility(View.VISIBLE);
                    }

                    yiShenHeListAdapter.setDataList(dataBeanList);

                    Log.d("YiShenHe", zhenBanShenHe.getData().size() + "");

                } else {
                    Toast.makeText(getActivity(), baseBean.getMessage(), Toast.LENGTH_SHORT).show();
                }

            }


            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                Log.d("ONERROR", "ONERROER");
                layout_nodata.setVisibility(View.VISIBLE);

            }

            @Override
            public void onAfter(String s, Exception e) {
                super.onAfter(s, e);
                refreshLayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                refreshLayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
            }
        });
    }

    public void getCaneda() {
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(2018, 0, 1);
        Calendar endDate = Calendar.getInstance();
        int y = endDate.get(Calendar.YEAR);
        int m = endDate.get(Calendar.MONTH);
        int d = endDate.get(Calendar.DATE);
        endDate.set(2033, 12, 31);
        pvTime = new TimePickerBuilder(getActivity(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                switch (v.getId()) {
                    case R.id.layout_calenda_first:
//                        textview_calendafirst.setText(getTime(date));

                        String replace_data = getTime(date).replace("-", ".");
                        Log.d("replace_data", replace_data);

                        startTime = getTime(date);

                        Integer i = startTime.compareTo(endTime);
                        if (i > 0) {
                            Toast.makeText(getActivity(), "开始时间不能大于结束时间", Toast.LENGTH_SHORT).show();
                        } else {
                            textview_calendafirst.setText(replace_data);
                            getMyData(token, "1", startTime, endTime);
                        }

                        break;
                    case R.id.layout_calenda_second:

                        endTime = getTime(date);
                        Integer i1 = startTime.compareTo(endTime);
                        if (i1 > 0) {
                            Toast.makeText(getActivity(), "开始时间不能大于结束时间", Toast.LENGTH_SHORT).show();
                        } else {
//                            textview_calendasecond.setText(getTime(date));
                            String replace_data1 = getTime(date).replace("-", ".");
                            Log.d("replace_data", replace_data1);
                            textview_calendasecond.setText(replace_data1);
                            getMyData(token, "1", startTime, endTime);
                        }

                        break;

                }

            }
        }).setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_lunar, new CustomListener() {

                    @Override
                    public void customLayout(final View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvTime.returnData();
                                pvTime.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvTime.dismiss();
                            }
                        });


                    }


                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(getResources().getColor(R.color.canedacolor))

                .build();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    private void initView() {
    }


    private void initListener() {
        yiShenHeListAdapter.setOnItemClickListener(this);

    }

    @OnClick({R.id.layout_calenda_first, R.id.layout_calenda_second, R.id.btn_digndan, R.id.btn_suofang, R.id.img_list})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.layout_calenda_first:
                pvTime.show(layout_calenda_first);
                break;
            case R.id.layout_calenda_second:
                pvTime.show(layout_calenda_second);
                break;
            case R.id.btn_digndan:
                SharePreferenceUtil.put(getActivity(), "modify", "0");
                startActivity(new Intent(getActivity(), ZhenBanDingDanActivity.class));
//                startActivity(new Intent(getActivity(), DingDanActivity.class));
                break;
            case R.id.btn_suofang:
                btn_digndan.setVisibility(View.GONE);
                btnSuofang.setVisibility(View.VISIBLE);
                imgList.setVisibility(View.VISIBLE);
                break;
            case R.id.img_list:
//                startActivity(new Intent(getActivity(), DingDanActivity.class));

                imgList.setVisibility(View.GONE);
                btn_digndan.setVisibility(View.VISIBLE);
                btnSuofang.setVisibility(View.VISIBLE);
                break;

        }
    }

    String mysendTime;

    @Override
    public void onItemClickListener(View view, int pos, YiShenHeListAdapter.ViewName viewName, List<ZhenBanShenHe.DataBean> myLiveLists) {
        Intent intent;
        switch (view.getId()) {

            case R.id.btn_zhuijia:
                Calendar selectedDate = Calendar.getInstance();//系统当前时间
                Calendar startDate = Calendar.getInstance();
                Calendar endDate = Calendar.getInstance();
                int y = endDate.get(Calendar.YEAR);
                int m = endDate.get(Calendar.MONTH);
                int d = endDate.get(Calendar.DATE);
                startDate.set(y, m, d);
                endDate.set(2021, 12, 12);
                pvTime2 = new TimePickerBuilder(getActivity(), new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        mysendTime = getTime(date);

                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
                        try {
                            Date date1 = simpleDateFormat.parse(myLiveLists.get(pos).getApplyTime());
                            boolean dateResult = date.after(date1);

                            String dateString = simpleDateFormat.format(date);
                            String dateString1 = simpleDateFormat.format(date1);
                            if (dateString.equals(dateString1)){
                                Log.d("同一天",  "同一天");
                                Toast.makeText(getActivity(), "当前时间为同一天", Toast.LENGTH_SHORT).show();
                            }else {
                                SharePreferenceUtil.put(getActivity(), "mysendTime", mysendTime);
                                EventBean eventBean = new EventBean();
                                eventBean.setSendStr(mysendTime);
                                eventBean.setSendCode(13);
                                EventBus.getDefault().post(eventBean);
                            }

                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                    }
                }).setDate(selectedDate)
                        .setRangDate(startDate, endDate)
                        .setLayoutRes(R.layout.pickerview_custom_lunar, new CustomListener() {
                            @Override
                            public void customLayout(final View v) {
                                final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                                ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                                tvSubmit.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        //                                        addNewData(myLiveLists.get(pos).getApplyId(),pvTime2.toString());
                                        pvTime2.returnData();
                                        pvTime2.dismiss();


                                    }
                                });
                                ivCancel.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        pvTime2.dismiss();
                                    }
                                });

                            }

                        })
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                        .setDividerColor(getResources().getColor(R.color.canedacolor))
                        .build();
                SharePreferenceUtil.put(getActivity(), "applyId", myLiveLists.get(pos).getApplyId());

                pvTime2.show();

                break;
            case R.id.btn_submit:
//                startActivity(new Intent(getActivity(), QueRenLingQuActivity.class));
                intent = new Intent(getActivity(), QueRenLingQuActivity.class);
                intent.putExtra("applyId", myLiveLists.get(pos).getApplyId());
//                applyTime
                intent.putExtra("applyTime", myLiveLists.get(pos).getApplyTime());
                startActivity(intent);
                break;
            case R.id.btn_chakan:
                intent = new Intent(getActivity(), CangKuListActivity.class);
                intent.putExtra("applyId", myLiveLists.get(pos).getApplyId());
                startActivity(intent);
                break;

            default:

                Intent intent2 = new Intent(getActivity(), YiShenHeActivity.class);
                intent2.putExtra("applyId", myLiveLists.get(pos).getApplyId());
//                applyTime
                intent2.putExtra("position", pos + "");
                intent2.putExtra("applyTime", myLiveLists.get(pos).getApplyTime());
                startActivity(intent2);

                break;

        }
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    public void onEventMainThread(EventBean eventBean) {
//        SharePreferenceUtil.put(getActivity(),"applyId",myLiveLists.get(pos).getApplyId());
//        SharePreferenceUtil.put(getActivity(),"mysendTime",mysendTime);
        String applyId = (String) SharePreferenceUtil.get(getActivity(), "applyId", "");
        String mysendTime = (String) SharePreferenceUtil.get(getActivity(), "mysendTime", "");

        Log.d("追加这里", "追加这里");
        if (eventBean.getSendCode() == 13) {
            Log.d("dkdkdked", eventBean.getSendStr());
        }

        if (eventBean.getSendCode() == 13) {
            addNewData(applyId, eventBean.getSendStr());
        }
    }

    public void addNewData(String applyId, String time) {
//        HttpResponse.addNewPrice(token, myLiveLists.get(pos).getApplyId(), getTime(date), new StringCallback(getActivity()) {
        HttpResponse.addNewPrice(token, applyId, time, new StringCallback(getActivity()) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("追加追加追加", s);
                BaseBean baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {

                    EventBus.getDefault().post(11);
                }
                Toast.makeText(getActivity(), baseBean.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

}